function diff=comparegroups( group1, group2, img1, img2, factor )
% diff=comparegroups( group1, group2, img1, img2 ) - calculates lumimnance
% diference between two groups, each from anotgher image.
% groups dimensions are multiplied by factor
% diff is 2D matrix of [0,1) values.

% get luminance
lumin1 = lumin( img1 );
lumin2 = lumin( img2 );


% get minimum size around group center

y1 = min( group1.centerY - group1.minY, group2.centerY - group2.minY );
y2 = min( group1.maxY - group1.centerY, group2.maxY - group2.centerY );

x1 = min( group1.centerX - group1.minX, group2.centerX - group2.minX );
x2 = min( group1.maxX - group1.centerX, group2.maxX - group2.centerX );

sy = 0;
sx = 0;

% subimage boundaries
w = ceil( ( x1 + x2 ) * factor );
h = ceil( ( y1 + y2 ) * factor );

ymin1 = floor( ( group1.centerY - y1 ) * factor ) + sy;
ymax1 = ymin1 + h;
xmin1 = floor( ( group1.centerX - x1 ) * factor ) + sx;
xmax1 = xmin1 + w;

ymin2 = floor( ( group2.centerY - y1 ) * factor );
ymax2 = ymin2 + h;
xmin2 = floor( ( group2.centerX - x1 ) * factor );
xmax2 = xmin2 + w;


% extract subimages
sub1 = lumin1( ymin1 : (ymin1+h) , xmin1 : (xmin1+w), : );
sub2 = lumin2( ymin2 : (ymin2+h) , xmin2 : (xmin2+w), : );

% create diff
diff = abs( sub1-sub2 );

% measurement - mean diff luminance
mean = sum( sum( diff ) ) / ( size( diff, 1 ) * size( diff, 2 ) )

% test - calculate hsv difference
% TEST RESULT - it is event worse!
% sub1hsv = rgb2hsv( img1( ymin1 : (ymin1+h) , xmin1 : (xmin1+w), : ) );
% sub2hsv = rgb2hsv( img2( ymin2 : (ymin2+h) , xmin2 : (xmin2+w), : ) );
% 
% diffhsv = abs( sub1hsv - sub2hsv );
% 
% mean hsv diff
%meanhsv = sum( sum( diffhsv ) ) / ( size( diffhsv, 1 ) * size( diffhsv, 2 ) )

% debug - shoiw
image( lumi2gray( diff ) );
hold on

plot( group1.centerX * factor - xmin1, group1.centerY * factor - ymin1, '+b' );
plot( group2.centerX * factor - xmin2, group2.centerY * factor - ymin2, '+g' );

hold off



